package com.jmemoir.safe.ratelimit.aspect;

import com.google.common.util.concurrent.RateLimiter;
import com.jmemoir.common.exception.ServiceException;
import com.jmemoir.safe.ratelimit.annotation.RateLimit;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 自定义限流切面
 *
 * @author Tellsea
 * @date 2023/8/14
 */
@Aspect
@Component
public class RateLimitAspect {

    /**
     * 默认每秒最大请求数为10
     */
    private final RateLimiter rateLimiter = RateLimiter.create(1);

    @Before("@annotation(rateLimit)")
    public void before(JoinPoint joinPoint, RateLimit rateLimit) throws Throwable {
        if (!rateLimiter.tryAcquire(rateLimit.value(), TimeUnit.SECONDS)) {
            throw new ServiceException("接口访问过于频繁，请稍后再试");
        }
    }
}